<?php
// +----------------------------------------------------------------------
// | ProjectName : domall
// +----------------------------------------------------------------------
// | Description :  订单模型
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.idowe.com All rights reserved.
// +----------------------------------------------------------------------
// | Authors : Johhny <chenjf@idowe.com>  Date : 2016-03-07
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Exception;
use think\Model;
class Orders extends Common{

    /**
     * 保存订单
     * @author Johhny <chenjf@idowe.com>
     */
    public function saveOrder($user_info){
        $cart_list = M('cart')->where(array('buyer_id'=>$user_info['member_id']))->select();

        $address_info = M('address')->where(array('member_id'=>$user_info['member_id'],'is_default'=>'1'))->find();

        if(!$cart_list){
            return array('error' => '购物车被清空，请重新选择商品！');
        }
        try{
            $this->db->startTrans();

            $order_goods = array();

            $store_cart_list = $this->_getStoreCartList($cart_list);

            $paySn = $this->makePaySn($user_info['member_id']);

            foreach($store_cart_list as $store_id => $goods_list){
                //保存订单表

                $order['order_sn'] = $this->makeOrderSn($user_info['member_id']);
                $order['pay_sn'] = $paySn;
                $order['store_id'] = $store_id;
                $order['store_name'] = $goods_list[0]['store_name'];
                $order['buyer_id'] = $user_info['member_id'];
                $order['buyer_name'] = $user_info['member_name'];
                $order['buyer_email'] = $user_info['member_email'];
                $order['buyer_phone'] = $address_info['mob_phone'];
                $order['add_time'] = time();
                $order['payment_code'] = "online";//online:在线支付，offline：货到付款
                $order['order_state'] = '10';

                $goods_total= 0;
                foreach ($goods_list as $goods_info) {
                    //计算商品金额
                    $goods_total = $goods_info['goods_price'] * $goods_info['goods_num'];
                }

                $order['order_amount'] = $goods_total;
                $order['shipping_fee'] = '0';//运费
                $order['goods_amount'] = $order['order_amount'] - $order['shipping_fee'];
                $order['order_from'] = '1';//1:WEB,2:mobile
                $order['order_type'] = '1';
                $order['chain_id'] = 0;
                $order['rpt_amount'] = 0;

                $order['reciver_address_id'] = $address_info['address_id'];
                $order['reciver_name'] = $address_info['true_name'];
                $order['reciver_area_name'] = $address_info['area_name'];
                $order['reciver_city_name'] = $address_info['city_name'];
                $order['reciver_area_info'] = $address_info['area_info'];
                $order['reciver_address'] = $address_info['address'];
                $order['reciver_tel_phone'] = $address_info['tel_phone'];
                $order['reciver_mob_phone'] = $address_info['mob_phone'];

                $order_id =  M('orders')->add($order);

                //保存订单商品表
                if($order_id){
                    $i = 0;
                    foreach ($goods_list as $goods_info) {
                        if (!intval($goods_info['bl_id'])) {
                            //如果不是优惠套装
                            $order_goods[$i]['order_id'] = $order_id;
                            $order_goods[$i]['goods_id'] = $goods_info['goods_id'];
                            $order_goods[$i]['store_id'] = $store_id;
                            $order_goods[$i]['goods_name'] = $goods_info['goods_name'];
                            $order_goods[$i]['goods_price'] = $goods_info['goods_price'];
                            $order_goods[$i]['goods_num'] = $goods_info['goods_num'];
                            $order_goods[$i]['goods_image'] = $goods_info['goods_image'];
//                            $order_goods[$i]['goods_spec'] = $goods_info['goods_spec'];
                            $order_goods[$i]['buyer_id'] = $user_info['member_id'];
                            $order_goods[$i]['goods_type'] = 1;
                            $order_goods[$i]['promotions_id'] = 0;

                            $order_goods[$i]['commis_rate'] = 200;
//                            $order_goods[$i]['gc_id'] = $goods_info['gc_id'];

                            //计算商品金额
                            $goods_total = $goods_info['goods_price'] * $goods_info['goods_num'];
                            //计算本件商品优惠金额
                            $order_goods[$i]['goods_pay_price'] = $goods_total;
                            $i++;
                        }
                    }

                    $insert = M('order_goods')->addAll($order_goods);
                    if (!$insert) {
                        return array('error' => '订单保存失败[未生成商品数据]');
                    }
                }else{
                    return array('error' => '保存订单失败');
                }
            }

            //清空购物车
            M('cart')->where(array('buyer_id'=>$user_info['member_id']))->delete();

            $this->db->commit();

            return $paySn;
        }catch (Exception $e) {
            $this->db->rollback();
            return array('error' => '保存订单失败');
        }

    }

    /**
     * 生成支付单编号(两位随机 + 从2000-01-01 00:00:00 到现在的秒数+微秒+会员ID%1000)，该值会传给第三方支付接口
     * 长度 =2位 + 10位 + 3位 + 3位  = 18位
     * 1000个会员同一微秒提订单，重复机率为1/100
     * @return string
     */
    private function makePaySn($member_id) {
        return mt_rand(10,99)
        . sprintf('%010d',time() - 946656000)
        . sprintf('%03d', (float) microtime() * 1000)
        . sprintf('%03d', (int) $member_id % 1000);
    }

    /**
     * 订单编号生成规则
     * @param $pay_id 支付表自增ID
     * @return string
     */
    public function makeOrderSn($member_id) {
        return (date('y',time()) % 9+1) . sprintf('%013d', (float) microtime() * 1000) . sprintf('%02d', (int) $member_id % 1000);
    }

    /**
     * 将下单商品列表转换为以店铺ID为下标的数组
     *
     * @param array $cart_list
     * @return array
     */
    private function _getStoreCartList($cart_list) {
        if (empty($cart_list) || !is_array($cart_list)) return $cart_list;
        $new_array = array();
        foreach ($cart_list as $cart) {
            $new_array[$cart['store_id']][] = $cart;
        }
        return $new_array;
    }

}